package com.web.handler;

import com.web.dao.LogLoginMapper;
import com.web.domain.MUser;
import com.web.entity.LogLogin;
import com.xkk.utils.IpAndCityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 *
 * @author Administrator
 * @date 2016/12/8
 */
@Slf4j
@Component
public class MyLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler {
    @Autowired
    private LogLoginMapper logLoginMapper;
    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        try {
            MUser user = (MUser)authentication
                    .getPrincipal();
            LogLogin logLogin=new LogLogin();
            logLogin.setContent("登出成功!");
            logLogin.setSignType("logout");
            logLogin.setUsername(user.getUsername());
            logLogin.setUserId(user.getId());
            logLogin.setSignIp(IpAndCityUtil.getIpAddr(httpServletRequest));
            logLogin.setSignAddress(IpAndCityUtil.getCityNameByIp(logLogin.getSignIp()).get("city").toString());
            logLogin.setSignTime(new Date());
            logLoginMapper.insertSelective(logLogin);
        } catch (Exception e) {
            e.printStackTrace();
        }
        handle(httpServletRequest,httpServletResponse,authentication);
    }
}